from openai import OpenAI

from ai.prompt import system_prompt, user_prompt
from utils.match import get_json_from_string
from utils.print_message import print_message

# 封装messages
def process_messages(data):
    system_content = system_prompt()
    user_content = user_prompt(data)
    return [
        {"role": "system", "content": system_content},
        {"role": "user", "content": user_content}
    ]

# 统一逻辑处理返回的内容
def process_content(content, ai_info):
    json_result = get_json_from_string(content)
    if not json_result:
        print_message(f"json转换失败，原文:{content}")
        return None
    return {
        **json_result,
        **ai_info
    }

# 通过使用openai获取的数据
def get_result_by_open_ai(data, ai_info):
    client = OpenAI(
        api_key = ai_info['api_key'],
        base_url = ai_info['url'],
    )
    
    completion = client.chat.completions.create(
        model = ai_info['model'],
        messages = process_messages(data),
        temperature = 0.1,
    )
    content = completion.choices[0].message.content
    return process_content(content, ai_info)
    




